﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;

namespace Pixysoft.Tools
{
    public class DiskHelper
    {
        private static volatile DiskHelper instance;

        private static object syncRoot = new Object();

        public static DiskHelper Instance
        {
            get
            {
                if (instance == null)
                {
                    lock (syncRoot)
                    {
                        instance = new DiskHelper();
                    }
                }

                return instance;

            }
        }

        public string GetDiskName(string path)
        {
            string disk = Regex.Match(path, "[\\w]{1}:\\\\", RegexOptions.IgnoreCase).Value;

            if (string.IsNullOrEmpty(disk))
                return path;

            return disk.Trim().ToUpper();
        }

        /// <summary>
        /// 取得空闲空间，MB单位
        /// </summary>
        /// <param name="diskName"></param>
        /// <returns></returns>
        public double GetFreeSpace(string diskName)
        {
            if (string.IsNullOrEmpty(diskName))
                return -1;

            System.IO.DriveInfo[] drives = System.IO.DriveInfo.GetDrives();

            foreach (DriveInfo info in drives)
            {
                if (info.Name.Trim().ToUpper() != diskName.Trim().ToUpper())
                    continue;

                return info.AvailableFreeSpace / 1000000;
            }

            return -1;
        }

        /// <summary>
        /// 长度转换
        /// </summary>
        /// <param name="length"></param>
        /// <returns></returns>
        public double ByteToMegaByte(double length)
        {
            return Math.Round(length / 1000000, 2);
        }

        private void test()
        {
            //Console.Write(GetFreeSpace(GetDiskName(@"c:\adf\asdf\asdf")));
            Console.WriteLine(ByteToMegaByte(123456789));
        }
    }
}
